package com.project_doctor.controller;

import com.project_doctor.service.impl.QRCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/qrcode")
@Api(tags = "二维码管理")
public class QRCodeController {

    @Autowired
    private QRCodeService qrCodeService;

    @Value("${qrcode.upload.path}")
    private String qrCodePath;

    /**
     * 生成签约信息二维码
     * 功能：生成签约信息图片并保存到本地，返回第三方在线二维码URL
     */
    @ApiOperation(value = "生成签约二维码", notes = "根据签约信息生成二维码图片")
    @PostMapping("/generateQRCode")
    public ResponseEntity<Map<String, Object>> generateQRCode(@RequestBody Map<String, Object> request) {
        Map<String, Object> response = new HashMap<>();

        try {
            // 参数获取和验证
            String contractId;
            Map<String, Object> contractData;

            // 兼容两种数据格式
            if (request.containsKey("contractData")) {
                // 格式1: {id: "7", contractData: {...}}
                contractId = request.get("id").toString();
                contractData = (Map<String, Object>) request.get("contractData");
            } else {
                // 格式2: 直接传入签约对象 {id: 7, name: "李四", ...}
                contractId = request.get("id").toString();
                contractData = request; // 直接使用整个请求对象作为数据
            }

            if (contractId == null || contractId.trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "签约ID不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            if (contractData == null || contractData.isEmpty()) {
                response.put("success", false);
                response.put("message", "签约数据不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            if (contractData.get("name") == null || contractData.get("name").toString().trim().isEmpty()) {
                response.put("success", false);
                response.put("message", "居民姓名不能为空");
                return ResponseEntity.badRequest().body(response);
            }

            // 调用服务生成二维码（生成图片文件 + 返回在线二维码URL）
            String qrCodeUrl = qrCodeService.generateContractQRCode(contractId, contractData);

            // 控制台输出二维码内容
            System.out.println("二维码生成成功 - 签约ID: " + contractId + ", 居民: " + contractData.get("name"));

            // 返回成功结果
            response.put("success", true);
            response.put("message", "二维码生成成功");
            response.put("qrCodeUrl", qrCodeUrl);
            response.put("contractId", contractId);
            response.put("residentName", contractData.get("name"));
            response.put("description", "扫码后将直接显示签约信息图片");

            return ResponseEntity.ok(response);

        } catch (IllegalArgumentException e) {
            response.put("success", false);
            response.put("message", "参数错误: " + e.getMessage());
            return ResponseEntity.badRequest().body(response);

        } catch (Exception e) {
            response.put("success", false);
            response.put("message", "二维码生成失败: " + e.getMessage());
            return ResponseEntity.status(500).body(response);
        }
    }

    /**
     * 返回签约信息图片文件
     * 用于扫码后直接显示签约信息
     */
    @ApiOperation(value = "获取签约信息图片", notes = "返回签约信息图片文件")
    @GetMapping("/image/{fileName}")
    public ResponseEntity<Resource> getImage(@PathVariable String fileName) {
        try {
            File file = new File(qrCodePath, fileName);

            if (!file.exists()) {
                return ResponseEntity.notFound().build();
            }

            Resource resource = new FileSystemResource(file);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.IMAGE_PNG);
            headers.add("Cache-Control", "max-age=3600");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(resource);

        } catch (Exception e) {
            return ResponseEntity.status(500).build();
        }
    }

    // 工作流程：
    // 1. POST /qrcode/generateQRCode -> 生成本地图片文件 + 返回在线二维码URL
    // 2. 扫码访问 -> GET /qrcode/image/{fileName} -> 直接显示签约信息图片
}
